<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-row :gutter="7" style="margin-bottom: 16px">
      <el-col :span="2.5">
        <div style="text-align: left">
          <el-button
            type="primary"
            plain
            @click="openStockList"
          >
            选择物料
          </el-button>
        </div>
      </el-col>
      <el-col :span="2.5">
        <div style="text-align: left">
          <el-button
            type="default"
            plain
            @click="batchFilling"
            :loading="exportLoading"
            v-hasPermi="['system:tenant:export']"
          >
            批量填充
          </el-button>
        </div>
      </el-col>
      <el-col :span="2.5">
        <div style="text-align: left">
          <el-button
            type="default"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['system:tenant:export']"
          >
            删除
          </el-button>
        </div>
      </el-col>
      <el-col :span="2.5">
        <div style="text-align: left">
          <el-button type="default" plain @click="btnLie" :loading="exportLoading">
            <img key="1" alt="" width="25px" height="20px" src="@/assets/svgs/column.svg" />
            列表字段
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-table border :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column type="selection" fixed="left" width="60" />
      <el-table-column label="序号" prop="sort" type="index" fixed="left" width="80" />
      <el-table-column label="物料编码" align="center" prop="MaterialCode" width="120" />
      <el-table-column label="物料名称" align="center" prop="MaterialName" width="120" />
      <el-table-column label="物料图" align="center" prop="MaterialImage" width="120" />
      <el-table-column label="物料规格" align="center" prop="MaterialSpec" width="120" />
      <el-table-column label="基本单位" align="center" prop="BaseUnit" width="120" />
      <el-table-column label="可用库存" align="center" prop="StockQty" width="120" />
      <el-table-column label="基本含税单价" align="center" prop="BasePriceTaxIn" width="120" />
      <el-table-column label="税率" align="center" prop="TaxRate" width="120" />
      <el-table-column label="基本不含税单价" align="center" prop="BasePriceTaxEx" width="120" />
      <el-table-column label="采购数量" align="center" prop="PurchaseQty" width="120" />
      <el-table-column label="检验状态" align="center" prop="InspectionStatus" width="120" />
      <el-table-column label="验收数量" align="center" prop="AcceptedQty" width="120" />
      <el-table-column label="报废数量" align="center" prop="ScrapQty" width="120" />
      <el-table-column label="拒收数量" align="center" prop="RejectedQty" width="120" />
      <el-table-column label="让步接收数量" align="center" prop="ConcessionQty" width="120" />
      <el-table-column label="入库仓库" align="center" prop="Warehouse" width="120" />
      <el-table-column label="版本" align="center" prop="Version" width="120" />
      <el-table-column label="克重" align="center" prop="Weight" width="120" />
      <el-table-column label="累计入库数量" align="center" prop="TotalReceived" width="120" />
      <el-table-column label="客户型号" align="center" prop="CustomerPN" width="120" />
      <el-table-column label="基本数量" align="center" prop="BaseQty" width="120" />
      <el-table-column label="产品图片" align="center" prop="ProductImage" width="120" />
      <el-table-column label="辅助单位" align="center" prop="AltUnit" width="120" />
      <el-table-column label="辅助数量" align="center" prop="AltQty" width="120" />
      <el-table-column label="辅助含税单价" align="center" prop="AltPriceTaxIn" width="120" />
      <el-table-column label="辅助不含税单价" align="center" prop="AltPriceTaxEx" width="120" />
      <el-table-column label="入库含税金额" align="center" prop="TaxInAmt" width="120" />
      <el-table-column label="生产日期" align="center" prop="MFGDate" width="120" />
      <el-table-column label="入库不含税金额" align="center" prop="TaxExAmt" width="120" />
      <el-table-column label="采购员" align="center" prop="Buyer" width="120" />
      <el-table-column label="整单折扣分配额" align="center" prop="TotalDiscount" width="120" />
      <el-table-column label="品牌" align="center" prop="Brand" width="120" />
      <el-table-column label="税额" align="center" prop="TaxAmt" width="120" />
      <el-table-column label="最低采购标准" align="center" prop="MOQ" width="120" />
      <el-table-column label="实际含税金额" align="center" prop="ActualTaxInAmt" width="120" />
      <el-table-column label="规格" align="center" prop="Specification" width="120" />
      <el-table-column label="实际含税单价" align="center" prop="ActualPriceTaxIn" width="120" />
      <el-table-column label="实际不含税金额" align="center" prop="ActualTaxExAmt" width="120" />
      <el-table-column label="实际不含税单价" align="center" prop="ActualPriceTaxEx" width="120" />
      <el-table-column label="已开票数量" align="center" prop="InvoicedQty" width="120" />
      <el-table-column label="未开票数量" align="center" prop="UninvoicedQty" width="120" />
      <el-table-column label="对等核销数量" align="center" prop="MatchedQty" width="120" />
      <el-table-column label="关联采购费用" align="center" prop="PurchaseCost" width="120" />
      <el-table-column label="基本单位成本" align="center" prop="BaseUnitCost" width="120" />
      <el-table-column label="入库成本" align="center" prop="InboundCost" width="120" />
      <el-table-column label="折扣率" align="center" prop="DiscountRate" width="120" />
      <el-table-column label="采购备注" align="center" prop="PurchaseNote" width="120" />
      <el-table-column label="行备注" align="center" prop="LineNote" width="120" />
      <el-table-column label="图号" align="center" prop="DrawingNo" width="120" />
      <el-table-column label="材质" align="center" prop="Material" width="120" />
      <el-table-column label="特性" align="center" prop="Characteristic" width="120" />
      <el-table-column label="螺纹" align="center" prop="ThreadSpec" width="120" />
      <el-table-column label="OEM1" align="center" prop="OEMRef1" width="120" />
      <el-table-column label="OEM2" align="center" prop="OEMRef2" width="120" />
      <el-table-column label="OEM3" align="center" prop="OEMRef3" width="120" />
      <el-table-column label="辅助单位成本" align="center" prop="AltUnitCost" width="120" />
      <el-table-column label="测试001" align="center" prop="TestField" width="120" />
      <el-table-column label="赠品" align="center" prop="IsGift" width="120" />
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <el-button @click="handleAdd" round>+ 添加物料</el-button>
  </el-row>

  <el-dialog v-model="dialogVisible" title="自定义字段" width="50%" :before-close="handleClose">
    (注: 列项显示不得少于5项，最多支持自定义10个列项，灰色选中列不支持隐藏和排序)
    <div class="content">
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.MaterialName" label="物料名称" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.MaterialImage" label="物料图" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.MaterialSpec" label="物料规格" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.BaseUnit" label="基本单位" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.StockQty" label="可用库存" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.BasePriceTaxIn" label="基本含税单价" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.TaxRate" label="税率" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.BasePriceTaxEx" label="基本不含税单价" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.InspectionStatus" label="采购数量" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.AcceptedQty" label="验收数量" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.ScrapQty" label="报废数量" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.RejectedQty" label="拒收数量" size="large"
      /></div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <StockForm
    ref="selectStockRef"
    @success="handleStockChange"
  />
    <batchFillingForm
    ref="batchFillingRef"
    @success="handleBatchChange"
  />
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { StockApi } from '@/api/erp/stock/stock'
import StockForm from './StockForm.vue'
import batchFillingForm from './batchFillingForm.vue'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue,
  underlineToHump
} from '@/utils'

const props = defineProps<{
  items: undefined
  disabled: false
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  inId: [{ required: true, message: '入库编号不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const defaultWarehouse = ref<WarehouseVO>(undefined) // 默认仓库
const visibleColumns = ref({
  MaterialName: true,
    MaterialImage: true,
    MaterialSpec: true,
    BaseUnit: true,
    AvailableQty: true,
    BasePriceWithTax: true,
    TaxRate: true,
    BasePriceExclTax: true,
    PurchaseQty: true,
    InspectionStatus: true,
    AcceptedQty: true,
    ScrapQty: true,
    RejectedQty: true,
    ConcessionQty: true,
    Warehouse: true,
    Version: true,
    Weight: true,
    TotalReceived: true,
    CustomerPN: true,
    BaseQty: true,
    ProductImage: true,
    AltUnit: true,
    AltQty: true,
    AltPriceWithTax: true,
    AltPriceExclTax: true,
    ReceivedAmtWithTax: true,
    MFGDate: true,
    ReceivedAmtExclTax: true,
    Buyer: true,
    TotalDiscount: true,
    Brand: true,
    TaxAmt: true,
    MOQ: true,
    ActualTaxInAmt: true,
    Specification: true,
    ActualPriceTaxIn: true,
    ActualTaxExAmt: true,
    ActualPriceTaxEx: true,
    InvoicedQty: true,
    UninvoicedQty: true,
    MatchedQty: true,
    PurchaseCost: true,
    BaseUnitCost: true,
    InboundCost: true,
    DiscountRate: true,
    PurchaseNote: true,
    LineNote: true,
    DrawingNo: true,
    Material: true,
    Characteristic: true,
    ThreadSpec: true,
    OEMRef1: true,
    OEMRef2: true,
    OEMRef3: true,
    AltUnitCost: true,
    TestField: true,
    IsGift: true
})
const dialogVisible = ref(false)
const tempVisibleColumns = ref({ ...visibleColumns.value })
const selectStockRef = ref() // 物料列表 Ref
const openStockList = () => {
  selectStockRef.value.open()
}
const batchFillingRef = ref() //批量填充 Ref
const batchFilling =()=>{
  console.log(4324324)
  batchFillingRef.value.open()
}
const btnLie = () => {
  tempVisibleColumns.value = { ...visibleColumns.value }
  dialogVisible.value = true
}
/** 初始化设置入库项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val
  },
  { immediate: true }
)

/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      item.totalPrice = erpPriceMultiply(item.productPrice, item.count)
    })
  },
  { deep: true }
)

/** 合计 */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'totalPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] =
        column.property === 'count' ? erpCountInputFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })

  return sums
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    sort: undefined,
    MaterialCode: undefined,
    MaterialName: undefined,
    MaterialImage: undefined,
    MaterialSpec: undefined,
    BaseUnit: undefined,
    AvailableQty: undefined,
    BasePriceWithTax: undefined,
    TaxRate: undefined,
    BasePriceExclTax: undefined,
    PurchaseQty: undefined,
    InspectionStatus: undefined,
    AcceptedQty: undefined,
    ScrapQty: undefined,
    RejectedQty: undefined,
    ConcessionQty: undefined,
    Warehouse: undefined,
    Version: undefined,
    Weight: undefined,
    TotalReceived: undefined,
    CustomerPN: undefined,
    BaseQty: undefined,
    ProductImage: undefined,
    AltUnit: undefined,
    AltQty: undefined,
    AltPriceWithTax: undefined,
    AltPriceExclTax: undefined,
    ReceivedAmtWithTax: undefined,
    MFGDate: undefined,
    ReceivedAmtExclTax: undefined,
    Buyer: undefined,
    TotalDiscount: undefined,
    Brand: undefined,
    TaxAmt: undefined,
    MOQ: undefined,
    ActualTaxInAmt: undefined,
    Specification: undefined,
    ActualPriceTaxIn: undefined,
    ActualTaxExAmt: undefined,
    ActualPriceTaxEx: undefined,
    InvoicedQty: undefined,
    UninvoicedQty: undefined,
    MatchedQty: undefined,
    PurchaseCost: undefined,
    BaseUnitCost: undefined,
    InboundCost: undefined,
    DiscountRate: undefined,
    PurchaseNote: undefined,
    LineNote: undefined,
    DrawingNo: undefined,
    Material: undefined,
    Characteristic: undefined,
    ThreadSpec: undefined,
    OEMRef1: undefined,
    OEMRef2: undefined,
    OEMRef3: undefined,
    AltUnitCost: undefined,
    TestField: undefined,
    IsGift: undefined
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 处理仓库变更 */
const onChangeWarehouse = (warehouseId, row) => {
  // 加载库存
  setStockCount(row)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productUnitName = product.unitName
    row.productBarCode = product.barCode
    row.productPrice = product.minPrice
  }
  // 加载库存
  setStockCount(row)
}

/** 加载库存 */
const setStockCount = async (row) => {
  if (!row.productId || !row.warehouseId) {
    return
  }
  const stock = await StockApi.getStock2(row.productId, row.warehouseId)
  row.stockCount = stock ? stock.count : 0
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
defineExpose({ validate })

/** 初始化 */
onMounted(async () => {
  productList.value = await ProductApi.getProductSimpleList()
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  defaultWarehouse.value = warehouseList.value.find((item) => item.defaultStatus)
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})
</script>
